/**
 * @ClassName: UserCartDao
 * @author linsen
 * @date 2016-10-11
 */
package com.fzrskj.cloud.free.user.dao;

import com.fzrskj.cloud.free.core.tool.CObjectTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.CloudDbDrvUtils;
import com.fzrskj.cloud.free.user.bean.UserCart;
import com.fzrskj.cloud.free.user.bean.UserCartView;
import ms.core.consts.SysErr;
import ms.core.db.IDbDrv;
import ms.core.object.CObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserCartDao extends CObject {

    private IDbDrv db = null;

    public UserCartDao() {
        db = CloudDbDrvUtils.getDbUtilsDrv();
    }

    //to free resource
    @Override
    public void dispose() {
        db.closeConnection();
    }

    //to add new record to database by bean
    public int addUserCart(UserCart obj) {
        //if (obj.getAgentId() == null){
            obj.setAgentId(CloudContextUtils.getAgentId());
        //}
        String sql = "insert into user_cart(applyTime,cartNo,cartTime,cartType,totalPrice,price," +
                "priceType,productClass,productCode,productParam,regType,userId," +
                "userName,businessId,agentId)" +
                "values(?,?,?,?,?,?," +
                "?,?,?,?,?,?," +
                "?,?,?);";
        Object[] prm = {obj.getApplyTime(), obj.getCartNo(), obj.getCartTime(), obj.getCartType(), obj.getTotalPrice(), obj.getPrice(),
                obj.getPriceType(), obj.getProductClass(), obj.getProductCode(), obj.getProductParam(), obj.getRegType(), obj.getUserId(),
                obj.getUserName(), obj.getBusinessId(), obj.getAgentId()};
        int ret = db.executeSql(sql, prm);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to add new record to database by map
    public int addUserCart(Map<String, Object> values) {
        //if (!values.containsKey("agentId")) {
            values.put("agentId", CloudContextUtils.getAgentId());
        //}
        int ret = db.insertRecord("user_cart", values);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to delete table record by id
    public int delUserCart(int id) {

        String sql = "delete from user_cart where id=? and agentId=?";
        int ret = db.executeSql(sql, new Object[]{id, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to delete table record by cdt
    public int delUserCart(Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        int ret = db.deleteRecord("user_cart", cdt);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to modify table record by values and condition
    public int modUserCart(Map<String, Object> values, Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        int ret = db.modifyRecord("user_cart", values, cdt);
        String code = db.getErrCode();
        this.setErrCode(code);
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }

        return ret;
    }

    //to query user_cart item for detail
    public UserCart queryUserCart(int id) {
        String sql = "select * from user_cart where id=? and agentId=?";
        UserCart ret = db.queryForBean(sql, UserCart.class, new Object[]{id, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to query UserCart record count
    public int queryUserCart(Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        int ret = db.queryRecordCount("user_cart", cdt);
        this.setErrCode(db.getErrCode());
        return ret;
    }

    //to query UserCart for record list with condition,if page or pagesize less than 0, means without page
    public List<UserCart> queryUserCartList(Map<String, Object> cdt, int page, int pagesize) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        Object[] params = new Object[cdt.size()];
        int i = 0;
        String sql = "select * from user_cart where 1=1";
        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            sql = sql + " and " + c.getKey() + "=?";
            params[i] = c.getValue();
            i++;
        }
        if (page > 0 && pagesize > 0) {
            sql += String.format(" limit %d,%d", (page - 1) * pagesize, pagesize);
        }
        List<UserCart> rets = db.queryForBeans(sql, UserCart.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return rets;
    }

    //查询购物车的数量
    public int queryUserCartCount(Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        Object[] params = new Object[cdt.size()];
        int i = 0;
        String sql = "select count(id) from user_cart where 1=1";
        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            sql = sql + " and " + c.getKey() + "=?";
            params[i] = c.getValue();
            i++;
        }
        Long ret = (Long) db.queryFieldValue(sql, Long.class, params, 1);
        this.setErrCode(db.getErrCode());
        if (ret == null) {
            return -1;
        }
        return ret.intValue();
    }

    //自定义方法(非生成)
    //获取购物车列表
    public List<UserCartView> getUserCartList(Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
        cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        Object[] params = new Object[cdt.size()];
        int i = 0;

        StringBuffer sql = new StringBuffer("select u.*,sp.productName,");
        sql.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='productclass' and t.value= u.productClass) as productClassName,");
        sql.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='orderType' and t.value= u.cartType) as cartTypeName ");
        sql.append("from user_cart u,sys_product sp where u.productCode=sp.productCode ");
        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            sql.append(" and u." + c.getKey() + "=?");
            params[i] = c.getValue();
            i++;
        }

        sql.append(" and sp.agentId=? " );
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId() );

        List<UserCartView> rets = db.queryForBeans(sql.toString(), UserCartView.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return rets;
    }

    //删除购物车
    public int delUserCart(int userId, List<String> list) {
        int ret = 0;
        for (String str : list) {
            String sql = "delete from user_cart where userId=? and cartNo=? and agentId=?";
            ret = db.executeSql(sql, new Object[]{userId, str, CloudContextUtils.getAgentId()});
            String code = db.getErrCode();
            if (!code.equals(SysErr.CODE_SUCCESS)) {
                this.log(db.getMsg());
            }
            this.setErrCode(code);
        }

        return ret;
    }

    //获取购物车
    public UserCart getUserCart(String cartNo) {
        String sql = "select * from user_cart where cartNo=? and agentId=?";
        UserCart ret = db.queryForBean(sql, UserCart.class, new Object[]{cartNo, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //购物车购买列表
    public List<UserCart> getUserCartBuyList(int userId, List<String> cartNos) {
        List<UserCart> list = new ArrayList<>();
        for (String str : cartNos) {
            String sql = "select * from user_cart where userId=? and cartNo=? and agentId=?";
            Object[] params = new Object[]{userId, str, CloudContextUtils.getAgentId()};
            UserCart obj = db.queryForBean(sql, UserCart.class, params);
            String code = db.getErrCode();
            if (!code.equals(SysErr.CODE_SUCCESS)) {
                this.log(db.getMsg());
            }
            this.setErrCode(code);

            list.add(obj);
        }
        return list;
    }

    /**
     * 查询已经逾期多少天的数据
     *
     * @param expiryDays
     * @param addTime
     * @return
     */
    public List<UserCart> arrearsUserCart(String expiryDays, String addTime) {
        //TODO
        String sql = "select * from user_cart where cartTime>=? and cartTime<? and agentId=?";
        List<UserCart> ret = db.queryForBeans(sql, UserCart.class, new Object[]{expiryDays, addTime, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    /**
     * 查询到期未生成订单
     *
     * @param dateTime
     * @return
     */
    public List<UserCart> queryExpireNoBuildOrder(String dateTime) {
        String sql = "select * from user_cart where Date(cartTime)<=Date(?) ";
        Object[] params = {dateTime};
        List<UserCart> ret = db.queryForBeans(sql, UserCart.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    /**
     * 根据用户名与参数查询购物车
     *
     * @param userName
     * @param productParam
     * @return
     */
    public List<UserCart> queryCart(String userName, String productParam, String cartType) {
        String sql = "select * from user_cart where productParam=? and userName=? and cartType=? and agentId=?";
        List<UserCart> queryCart = db.queryForBeans(sql, UserCart.class, new Object[]{productParam, userName, cartType, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return queryCart;
    }

    //查询购物车符合条件的数量
    public int queryUserCartExistCount(Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        List<Object> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select count(id) from user_cart where 1=1 ");
        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            if (c.getKey().equals("instanceId")) {
                sb.append(" and LOCATE(?,productParam)>0");
                list.add(c.getValue());
            } else if (c.getKey().equals("diskId")) {
                sb.append(" and LOCATE(?,productParam)>0");
                list.add(c.getValue());
            } else {
                sb.append(" and " + c.getKey() + "=?");
                list.add(c.getValue());
            }
        }

        Object[] params = new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }

        Long ret = (Long) db.queryFieldValue(sb.toString(), Long.class, params, 1);
        this.setErrCode(db.getErrCode());
        if (ret == null) {
            return -1;
        }
        return ret.intValue();
    }
}
